package com.future.allUtils.utils;

import com.future.domain.LoginUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;


/**
 * @author huayue
 *
 *   session不用了，怎么获取登录用户信息呢？
 *   -->从SecurityContextHolder中获取
 *   简化代码如下
 *    LoginUserDetails principal =
 *              (LoginUserDetails) SecurityContextHolder
 *              .getContext()
 *              .getAuthentication()
 *              .getPrincipal();
 *    太麻烦了，因此我封装了SecurityUtil类，返回值为LoginUserDetails
 *    LoginUserDetails 这个类你们自己看看，里面属性有User和权限信息
 *    通过这个类 就可以获取登录用户的信息了
 *
 */

public class SecurityUtils {
    /**
     * 获取当前登录用户的 userId
     */
    public static Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new RuntimeException("用户未登录");
        }
        LoginUserDetails principal1 = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        Object principal = authentication.getPrincipal();
        if (!(principal instanceof LoginUserDetails)) {
            throw new RuntimeException("用户信息格式错误");
        }

        return ((LoginUserDetails) principal).getUser().getId();
    }

    /**
     * 获取当前登录用户的完整信息为 LoginUserDetails 类型
     */
    public static LoginUserDetails getCurrentUser() {
        // 逻辑类似，返回 LoginUserDetails 对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new RuntimeException("用户未登录");
        }

        Object principal = authentication.getPrincipal();
        if (!(principal instanceof LoginUserDetails)) {
            throw new RuntimeException("用户信息格式错误");
        }

        return (LoginUserDetails) principal;
    }
}